package ru.store.book;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import ru.store.IStore;
import ru.store.Item;


public class BookStoreService implements IBookStore {
	Map<String, List<Book>> booksByTitle = new HashMap<String, List<Book>>();
	Map<String, List<Book>> booksByAuthor = new HashMap<String, List<Book>>();
	Map<String, List<Book>> booksByName = new HashMap<String, List<Book>>();
	
	private IStore store = null;
	
	public BookStoreService(IStore store) {
		this.store = store;
	}

	@Override
	public int getTotalAmount() {
		return booksByAuthor.size();
	}

	private void SyncMap()
	{
		Map<String, Item> map = store.getItems("book");
		List<Book> list; 
		
		booksByTitle.clear();
		booksByAuthor.clear();
		booksByName.clear();
		if (map == null)
			return;
		
		for (Item item: map.values()) {
			Book book = (Book)item;
			
			list = booksByTitle.get(book.getTitle());
			if ( list == null )
				list = new LinkedList<Book>();
			list.add(book);
			booksByTitle.put(book.getTitle(), list);
			
			list = booksByName.get(book.toString());
			if ( list == null )
				list = new LinkedList<Book>();
			list.add(book);
			booksByName.put(book.toString(), list);
			
			list = booksByAuthor.get(book.getAuthor());
			if ( list == null )
				list = new LinkedList<Book>();
			list.add(book);
			booksByAuthor.put(book.getAuthor(), list);
		}
	}
	
	@Override
	public void addBook(Book book) throws Exception {
		store.addItem(book);
		SyncMap();
	}

	@Override
	public List<String> getAuthors() {
		List<String> authors = new LinkedList<String>();
		authors.addAll(booksByAuthor.keySet());
		return authors;
	}

	@Override
	public List<String> getTitles() {
		List<String> result = new LinkedList<String>();
		result.addAll(booksByName.keySet());
		return result;
	}

	@Override
	public List<Book> findByAuthor(String author) {
		return booksByAuthor.get(author); 
	}

	@Override
	public List<Book> findByTitle(String title) {
		return booksByTitle.get(title); 
	}

	public void sellBook(String isdn, int count) throws Exception {
		store.sellItem("book", isdn, count);
		SyncMap();
	}
	
}
